﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ExcellOnServices.Models;
using PagedList;
using ExcellOnServices.Models.Utils;
using ExcellOnServices.Mailers;

namespace ExcellOnServices.Areas.Admin.Controllers
{
    public class OrdersController : Controller
    {
        private ExcellOnServicesContext db = new ExcellOnServicesContext();

        // GET: /Admin/Orders/
        [Authorize]
        public ActionResult Index(string search = null, string status = null, int page = 1)
        {
            //Set canceled for orders which didn't pay and set expried
            foreach (Order or in db.Orders)
            {
                if (or.Status == Order.StatusOrder.Confirmed && or.BeginDateTime < DateTime.Now)
                {
                    or.Status = Order.StatusOrder.Canceled;
                    db.SaveChanges();
                }
                if (or.Status == Order.StatusOrder.Activated && or.EndDateTime < DateTime.Now)
                {
                    or.Status = Order.StatusOrder.Expired;
                    foreach (OrderItem orItem in or.OrderItems)
                    {
                        orItem.Product.Published = false;
                    }
                    db.SaveChanges();
                }
            }

            var orders = db.Orders.Select(a => a);

            if (!String.IsNullOrEmpty(search))
            {
                orders = orders.Where(s => s.OrderItems.FirstOrDefault().Product.Accounts_Company.BrandName.ToUpper().Contains(search.ToUpper()));
            }
            if (!String.IsNullOrEmpty(status))
            {
                int statusID = (int)Enum.Parse(typeof(Order.StatusOrder), status);
                orders = orders.Where(s => (int)s.Status == statusID);
            }
            IEnumerable<Order.StatusOrder> statusList = Enum.GetValues(typeof(Order.StatusOrder)).OfType<Order.StatusOrder>();

            ViewBag.Status = new SelectList(statusList);
            ViewBag.StatusName = status;
            ViewBag.SearchString = search;
            ViewBag.Page = page;

            return View(orders.OrderBy(s => s.Status).Select(s => s).ToPagedList(page, 10));
        }

        [Authorize]
        public ActionResult EditStatus(int? id, string search, string status, int? page, int[] ckPublish = null)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            else
            {
                if (order.Status == Order.StatusOrder.Pending)
                {
                    if (ckPublish != null)
                    {
                        List<OrderItem> delOrItem = new List<OrderItem>();
                        bool isPublish = false;
                        // Remove products which admin want to unpublish
                        foreach (OrderItem orItem in order.OrderItems)
                        {
                            foreach (int ckItem in ckPublish)
                            {
                                if (orItem.Product.Id == ckItem)
                                {
                                    isPublish = true;
                                }
                            }
                            if (!isPublish)
                            {
                                delOrItem.Add(orItem);
                            }
                            isPublish = false;
                        }
                        foreach (OrderItem item in delOrItem)
                        {
                            db.OrderItems.Remove(item);
                        }
                    }
                    order.Status = Order.StatusOrder.Confirmed;
                    db.SaveChanges();
                    //Send mail to company
                    IMailer mailer = new Mailer();
                    mailer.ConfirmOrderMail(order).Send();
                }
                else if (order.Status == Order.StatusOrder.Confirmed)
                {
                    foreach (OrderItem orItem in order.OrderItems)
                    {
                        orItem.Product.Published = true;
                    }
                    order.Status = Order.StatusOrder.Activated;
                    db.SaveChanges();
                }
                return RedirectToAction("Index", new { search = search, status = status, page = page });
            }
        }

        // GET: /Admin/Orders/Details/5
        [Authorize]
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            return View(order);
        }

        [Authorize]
        public ActionResult Report(string searchFromDate = null, string searchToDate = null, string status = null, int page = 1)
        {
            var orders = db.Orders.Where(or => or.Status == Order.StatusOrder.Activated || or.Status == Order.StatusOrder.Expired);

            DateTime startDate = new DateTime();
            DateTime endDate = new DateTime();

            if (!String.IsNullOrEmpty(searchFromDate))
            {
                startDate = DateTime.Parse(searchFromDate);
            }
            if (!String.IsNullOrEmpty(searchToDate))
            {
                endDate = DateTime.Parse(searchToDate);
            }
            if (String.IsNullOrEmpty(searchFromDate) && !String.IsNullOrEmpty(searchToDate))
            {
                orders = orders.Where(s => s.BeginDateTime <= endDate);
            }
            else if (!String.IsNullOrEmpty(searchFromDate) && String.IsNullOrEmpty(searchToDate))
            {
                orders = orders.Where(s => s.BeginDateTime >= startDate);
            }
            else if (!String.IsNullOrEmpty(searchFromDate) && !String.IsNullOrEmpty(searchToDate))
            {
                orders = orders.Where(s => s.BeginDateTime >= startDate && s.BeginDateTime <= endDate);
            }
            if (!String.IsNullOrEmpty(status))
            {
                int statusID = (int)Enum.Parse(typeof(Order.StatusOrder), status);
                orders = orders.Where(s => (int)s.Status == statusID);
            }
            IEnumerable<Order.StatusOrder> statusList = Enum.GetValues(typeof(Order.StatusOrder)).OfType<Order.StatusOrder>();

            ViewBag.Status = new SelectList(statusList);
            ViewBag.StatusName = status;
            ViewBag.SearchFromDate = searchFromDate;
            ViewBag.SearchToDate = searchToDate;
            ViewBag.Page = page;

            return View(orders.OrderBy(s => s.Status).Select(s => s).ToPagedList(page, 10));
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
